#include "stdafx.h"

#pragma warning(disable: 4786)
#include <Magick++.h>

//using namespace Magick; 

#include "Twister.h"
#include "FileList.h"
#include "ImageThread.h"

#define BUFSIZE 65536

HANDLE	interruptEvent;
DWORD	rotateTime;
string	imageDirectory;


UINT ImageThread(LPVOID pParam)
{
	string originalDirectory;
	
	for (;;)
	{
		// Now do the load of the images
		ImageFileList fileList(imageDirectory);

		int fileCount(0);
		fileCount = fileList.listSize();

		if (fileCount)
		{
			bool setWallpaper = false;
			for (int tries = 0; tries < 10; ++tries)
			{
				string fileToUse;
				int num = 0;

				MTRand twister(::GetTickCount());
				num = twister.randInt() % fileCount;
		
				fileList.getFile(num, fileToUse);

				// Stick with a single name to identify our wallpaper, but this may have to be changed
				// if we're trying to set it to a new one (like on a timer) in which case we'll need to
				// use a new name, set it, then delete the old one (presumably there's a way to find out
				// what the old wallpaper is, though we would need to make sure we're not deleting a
				// windows bitmap
				string fileName("c:/windows/zestybits.bmp");

				// Now begins the ImageMagick++ stuff
				Magick::Image image;
				image.read(fileToUse.c_str());
						
				image.resolutionUnits(Magick::PixelsPerInchResolution);
				image.density(Magick::Geometry(72, 72)); 
				//double d1 = image.xResolution();
				//double d2 = image.yResolution();
				image.magick("BMP");
				image.write(fileName.c_str());

				if (SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, (char*)fileName.c_str(), SPIF_UPDATEINIFILE | SPIF_SENDCHANGE) == TRUE)
				{
					setWallpaper = true;
					break;
				}
			}

			if (setWallpaper == false)
			{
				AfxMessageBox("Hmm...couldn't set the wallpaper after 10 tries!");
			}
		}

		// * 1000 to get to seconds, then 60 to get to minutes
		::WaitForSingleObject(interruptEvent, (rotateTime * 1000 * 60));
	}

	return 0;
}